package com.meida.module.bus.provider.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.security.OpenUser;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.mapper.BusRecDeliveryViewMapper;
import com.meida.module.bus.provider.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * VIEW接口实现类
 *
 * @author flyme
 * @date 2020-12-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusRecDeliReqViewServiceImpl extends BaseServiceImpl<BusRecDeliveryViewMapper, BusRecDeliveryView> implements BusRecDeliReqViewService {

    @Autowired
    private BusRecDeliReqService busRecDeliReqService;
    @Autowired
    private BusMaterialPlan200Service plan200Service;
    @Autowired
    private PmsApiUtil pmsApiUtil;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusRecDeliveryView brdv, EntityMap extra) {
        return ResultBody.ok();
    }

    @Override
    public void afterPageList(CriteriaQuery<BusRecDeliveryView> cq, List<EntityMap> data, ResultBody resultBody) {
        System.out.println(data.size());
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusRecDeliveryView> cq, BusRecDeliveryView brdv, EntityMap requestMap) {
        cq.like(BusRecDeliveryView.class, "projectCode");
        cq.like(BusRecDeliveryView.class, "projectName");
        cq.like(BusRecDeliveryView.class, "userName");
        cq.eq(BusRecDeliveryView.class, "receivedDate");
        cq.like(BusRecDeliveryView.class, "supplierCode");
        cq.like(BusRecDeliveryView.class, "supplierName");
        cq.like(BusRecDeliveryView.class, "reserveNo");
        cq.like(BusRecDeliveryView.class, "reserveRow");
        cq.like(BusRecDeliveryView.class, "materialWbsCode");
        cq.like(BusRecDeliveryView.class, "materialCode");
        cq.like(BusRecDeliveryView.class, "materialName");
        cq.like(BusRecDeliveryView.class, "materiaSpecs");
        cq.like(BusRecDeliveryView.class, "technicalData");
        cq.like(BusRecDeliveryView.class, "levelNo");
        cq.like(BusRecDeliveryView.class, "materialArea");
        cq.like(BusRecDeliveryView.class, "measurementUnit");
        cq.like(BusRecDeliveryView.class, "materialUse");

        cq.like(BusRecDeliveryView.class, "packageNo");
        cq.like(BusRecDeliveryView.class, "packageName");

        List<String> majorCodes = pmsApiUtil.getAuthMajorCodes(OpenHelper.getUserId());
        if(null != majorCodes) {
            cq.in("brdv.majorCode", majorCodes);
        }
        List<String> projectCodeList = pmsApiUtil.getAuthProjectIds(OpenHelper.getUserId());
        if(null != projectCodeList) {
            cq.in("brdv.projectCode", projectCodeList);
        }
        cq.isNotNull(Boolean.TRUE, "reserveNo");
        cq.gt("receiveNum", "0");
        cq.orderByDesc("brdv.createTime");
        return ResultBody.ok();
    }

    @Override
    public void recDeliveryMk(List<BusRecDeliveryView> busRecDeliveryViewList) {
        BusSupplier busSupplier = pmsApiUtil.getBusSupplier(null, busRecDeliveryViewList.get(0).getSupplierCode());
        List<Long> inIns = Lists.newArrayList();
        Map<Long, BigDecimal> thisCountMap = Maps.newHashMap();
        busRecDeliveryViewList.stream().forEach(inObj -> {
            inIns.add(inObj.getPurchaseDetailsId());
            thisCountMap.put(inObj.getPurchaseDetailsId(), inObj.getRecNumThis());
        });

        Map<String, Object> searchMap = Maps.newHashMap();

        Collection<BusRecDeliveryView> inLists = listByIds(inIns);
        inLists.stream().forEach(inObj -> {
            inObj.setRecNumThis(thisCountMap.get(inObj.getPurchaseDetailsId()));
        });

        OpenUser user = OpenHelper.getUser();
        List<BusReceiptDeliveryReq> upds = Lists.newArrayList();
        inLists.stream().forEach(inObj -> {
            BusReceiptDeliveryReq updObj = new BusReceiptDeliveryReq();
            BeanUtil.copyProperties(inObj, updObj);
            // 可冲销数量
            updObj.setCharOffCountCan(inObj.getRecNumThis());
            updObj.setStatus(ApiConstants.REC_DELIVERY_RQ_INT);
            updObj.setAppTime(inObj.getCreateTime());
            updObj.setCreateUserId(user.getUserId());
            updObj.setCreateUserName(user.getUsername());
            updObj.setDelFlg(ApiConstants.DEL_OFF);
            if (!pmsApiUtil.getLastVer(inObj.getProjectId(), 0)) {
                Map<String, Object> searMap = Maps.newHashMap();
                searMap.put(ApiConstants.MAP_PACKAGEPLAN100IDP, updObj.getMaterialPlanId());
                Collection<BusMaterialPlan200> plan200s = plan200Service.listByMap(searMap);
                if (0 < plan200s.size()) {
                    BusMaterialPlan200 plan200Obj = plan200s.stream().findFirst().get();
                    updObj.setMaterialPlanId(plan200Obj.getMaterialPlanId());
                    updObj.setMaterialId(plan200Obj.getMaterialId());
                }
            }
            updObj.setSupplierCodeForRecord(busSupplier.getSupplierCode());
            updObj.setSupplierNameForRecord(busSupplier.getSupplierName());
            // 可出库数量
            updObj.setAvailableQty(inObj.getRecNumThis());
            // 已出库数量
            updObj.setIssuedQty(BigDecimal.ZERO);
            upds.add(updObj);
        });
        if (0 < upds.size()) {
            busRecDeliReqService.saveBatch(upds);
        }
    }

    @Override
    public ResultBody getMaterialPackageMajorList(Long projectId, int kind, String majorCode, String packageCode) {
        ResultBody rs = new ResultBody();
        if(2 == kind) {
            rs.data(pmsApiUtil.getBusProjectSuppliersForDelivery(projectId, majorCode, packageCode));
        } else {
            rs.data(pmsApiUtil.getMaterialPackageMajorList(projectId, kind, majorCode));
        }
        rs.isOk();
        return rs;
    }
}
